package com.chen.staffjoy.company.controller;

import com.chen.staffjoy.account.client.AccountClient;
import com.chen.staffjoy.account.dto.AccountDto;
import com.chen.staffjoy.account.dto.CreateAccountRequest;
import com.chen.staffjoy.account.dto.GenericAccountResponse;
import com.chen.staffjoy.commonlib.auth.AuthConstant;
import com.chen.staffjoy.commonlib.error.BusinessServiceException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * Account 服务调用验证
 * @author ChenTian
 * @date 2022/4/11
 */
@Slf4j
@RestController
@RequestMapping("/account/client")
@Validated
public class AccountDemoController {

    @Resource
    private AccountClient accountClient;

    @PostMapping("/create")
    public GenericAccountResponse createAccount(@RequestBody @Valid CreateAccountRequest request){
        GenericAccountResponse resp = null;

        try {
            resp = accountClient.createAccount(AuthConstant.AUTHORIZATION_COMPANY_SERVICE, request);
        } catch (Exception ex) {
            String errMsg = "could not create account";
            handleErrorAndThrowException(log, ex, errMsg);
        }
        if (!resp.isSuccess()) {
            handleErrorAndThrowException(log, resp.getMessage());
        }
        AccountDto account = resp.getAccount();
        GenericAccountResponse response = new GenericAccountResponse(account);
        return response;

    }

    @GetMapping("/getAccount")
    public GenericAccountResponse getAccount(String userId){
        GenericAccountResponse resp = null;
        try {
            resp = accountClient.getAccount(AuthConstant.AUTHORIZATION_COMPANY_SERVICE, userId);
        } catch (Exception ex) {
            String errMsg = "could not get account";
            handleErrorAndThrowException(log, ex, errMsg);
        }
        if (!resp.isSuccess()) {
            handleErrorAndThrowException(log, resp.getMessage());
        }
        AccountDto account = resp.getAccount();
        GenericAccountResponse response = new GenericAccountResponse(account);
        return response;
    }


    private void handleErrorAndThrowException(Logger log, String errMsg) {
        log.error(errMsg);
        throw new BusinessServiceException(errMsg);
    }

    private void handleErrorAndThrowException(Logger log, Exception ex, String errMsg) {
        log.error(errMsg, ex);
        throw new BusinessServiceException(errMsg, ex);
    }

}
